using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Notifications;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Models.DTOModel;
using AvaloniaApplication1.Util;
using AvaloniaApplication1.ViewModels.CardViewModel;
using AvaloniaApplication1.Views.CardView;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Controls;
using SukiUI.Controls.GlassMorphism;
using SukiUI.Dialogs;

namespace AvaloniaApplication1.ViewModels;

public partial class DevicePageViewModel : ObservableObject
{
    /// <summary>
    /// Mqtt设备管理器
    /// </summary>
    [ObservableProperty] private IMqttDeviceManager _deviceManager;

    /// <summary>
    /// Device设备连接状态
    /// </summary>
    [ObservableProperty] private bool _mqttisconneted;

    /// <summary>
    /// 搜索设备字符串
    /// </summary>
    [ObservableProperty] private string? _searchDeviceString = string.Empty;

    /// <summary>
    /// Mqtt设备列表
    /// </summary>
    [ObservableProperty] private ObservableCollection<MqttDeviceCardViewModel> _mqttDeviceItems;


    /// <summary>
    /// dialog管理器
    /// </summary>
    [ObservableProperty] private ISukiDialogManager _dialogManager;

    private AddDeviceDialogViewModel AddDeviceDialogVm { get; }

    public DevicePageViewModel(IMqttDeviceManager deviceManager, ISukiDialogManager dialogManager,
        AddDeviceDialogViewModel addDeviceDialogViewModel)
    {
        DeviceManager = deviceManager;

        //注入DialogManager
        DialogManager = dialogManager;
        AddDeviceDialogVm = addDeviceDialogViewModel;

        _ = InitializeMqttDevicesAsync();
    }

    private async Task InitializeMqttDevicesAsync()
    {
        // 创建主题配置列表
        var topicsOption1 = new List<MqttTopicConfig>
        {
            new("modbus/test1", 0, isSubscription: true, isPublish: false),
            new("modbus/test2", 0, isSubscription: true, isPublish: false)
        };

        var topicsOption2 = new List<MqttTopicConfig>
        {
            new("sensor/test1", 0, isSubscription: true, isPublish: false),
            new("sensor/test2", 0, isSubscription: true, isPublish: false)
        };

        // 添加设备
        await DeviceManager.AddDeviceAsync("device1", "172.16.2.22", 8630, "avatest", "home123", topicsOption1);
        await DeviceManager.AddDeviceAsync("device2", "172.16.2.22", 8630, "avatest1", "home123", topicsOption2);

        // 连接设备
        await DeviceManager.ConnectDeviceAsync("device1");
        await DeviceManager.ConnectDeviceAsync("device2");


        if (DeviceManager.IsDeviceConnected("device1") && DeviceManager.IsDeviceConnected("device2"))
        {
            Mqttisconneted = true;
        }

        //绑定设备卡片列表
        var deviceModels = DeviceManager.GetAllDevices();
        // 获取每个设备的deviceModels的DeviceId，创建一个MqttDeviceCardViewModel对象，添加到MqttDeviceItems中
        // MqttDeviceItems = new ObservableCollection<MqttDeviceCardViewModel>(
        //     deviceModels.Select(d => new MqttDeviceCardViewModel(d, DeviceManager, DialogManager))
        // );
        MqttDeviceItems = new ObservableCollection<MqttDeviceCardViewModel>();
        foreach (var deviceModel in deviceModels)
        {
            var mqttDeviceCardViewModel = new MqttDeviceCardViewModel(deviceModel, DeviceManager, DialogManager);
            mqttDeviceCardViewModel.OnRemoveMqttDevice += (sender) =>
            {
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    // 从 MqttDeviceItems 中移除该设备，UI同步更新
                    MqttDeviceItems.Remove(sender);
                });
            };
            MqttDeviceItems.Add(mqttDeviceCardViewModel);
        }
    }

    /// <summary>
    /// 添加设备对话框
    /// </summary>
    [RelayCommand]
    public void ShowAddDeviceDialog()
    {
        // 确保在 UI 线程执行
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            // 直接创建对话框内容视图，不设置 DataContext (不绑定 ViewModel)
            var dialogView = new AddDeviceDialogView
            {
                DataContext = AddDeviceDialogVm
            };
            AppLogger.Information($"{nameof(DevicePageViewModel)}-success-in-show");
            // 直接显示简单消息框
            var dialog = DialogManager.CreateDialog()
                .WithContent(dialogView)
                .Dismiss().ByClickingBackground()
                .WithActionButton("取消", _ => { DialogManager.DismissDialog(); })
                .WithActionButton("添加", async (_) =>
                {
                    var mqttCardModel = AddDeviceDialogVm.MqttCardModel;
                    if (!string.IsNullOrWhiteSpace(mqttCardModel.DeviceId) &&
                        !string.IsNullOrWhiteSpace(mqttCardModel.Server) &&
                        !string.IsNullOrWhiteSpace(mqttCardModel.Username)
                        && !string.IsNullOrWhiteSpace(mqttCardModel.Password)
                        && mqttCardModel.Port is > 0 and <= 65535 && mqttCardModel.Topics.Count > 0
                       )
                    {
                        // 实际添加设备逻辑
                        await DeviceManager.AddDeviceAsync(
                            mqttCardModel.DeviceId,
                            mqttCardModel.Server,
                            mqttCardModel.Port,
                            mqttCardModel.Username,
                            mqttCardModel.Password,
                            mqttCardModel.Topics
                        );

                        // 创建MqttDeviceModel（将MqttCardModel转换为MqttDeviceModel）
                        var mqttDeviceModel = mqttCardModel.ToMqttDeviceModel();
                        MqttDeviceItems.Add(new MqttDeviceCardViewModel(mqttDeviceModel, DeviceManager, DialogManager));
                        AppLogger.Information($"{nameof(DevicePageViewModel)}-success-add-currentTime-{DateTime.Now}");
                    }
                    else
                    {
                        await ShowValidationError();
                        AppLogger.PublicError($"AddMqttDevice Validation Error-currentTime-{DateTime.Now}");
                    }
                }, true)
                .ShowCardBackground(true).TryShow();
        });
    }

    private async Task ShowValidationError()
    {
        Dispatcher.UIThread.InvokeAsync(() =>
        {
            DialogManager.CreateDialog()
                .WithContent("添加失败，请检查端口或其他参数填写是否填写完整")
                .WithActionButton("确定", _ => { DialogManager.DismissDialog(); }).OfType(NotificationType.Error)
                .TryShow();
        });
    }

    [RelayCommand]
    public async Task SearchDeviceButtonClick()
    {
        try
        {
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                if (SearchDeviceString == null)
                {
                    MqttDeviceItems.Clear();
                    var deviceModels = DeviceManager.GetAllDevices();
                    // 空字符串 默认显示全部设备
                    foreach (var deviceModel in deviceModels)
                    {
                        var mqttDeviceCardViewModel =
                            new MqttDeviceCardViewModel(deviceModel, DeviceManager, DialogManager);
                        MqttDeviceItems.Add(mqttDeviceCardViewModel);
                        SearchDeviceString = null;
                    }
                    return;
                }
                var selectDevice= DeviceManager.GetDevice(SearchDeviceString);
                if (selectDevice != null)
                {
                    MqttDeviceItems.Clear();
                    MqttDeviceItems.Add(new MqttDeviceCardViewModel(selectDevice, DeviceManager, DialogManager));
                    SearchDeviceString = null;
                }
                else
                {
                    DialogManager.CreateDialog()
                        .WithContent("未找到该设备,请确定设备ID输入正确")
                        .WithActionButton("确定", _ => { DialogManager.DismissDialog(); }).OfType(NotificationType.Error)
                        .TryShow();
                }
            });
        }
        catch (Exception e)
        {
            AppLogger.Error(e, $"Error in SearchDeviceButtonClick currentTime-{DateTime.Now}");
            throw;
        }
    }


    // 添加连接切换命令
    [RelayCommand]
    private async Task ToggleDeviceConnectionAsync()
    {
        try
        {
            // 直接检查设备实际连接状态，而不是依赖Mqttisconneted属性
            bool isCurrentlyConnected = DeviceManager.IsDeviceConnected("device1") &&
                                        _deviceManager.IsDeviceConnected("device2");

            if (isCurrentlyConnected)
            {
                // 断开连接
                AppLogger.Information($"DebugMessageForm：{nameof(DevicePageViewModel)}-Disconnecting devices");
                await DeviceManager.DisconnectDeviceAsync("device1");
                await DeviceManager.DisconnectDeviceAsync("device2");
            }
            else
            {
                // 重新连接
                await DeviceManager.ConnectDeviceAsync("device1");
                await DeviceManager.ConnectDeviceAsync("device2");
            }
        }
        catch (Exception ex)
        {
            AppLogger.Error(ex, "Failed to toggle device connection");
        }
        finally
        {
            // 确保在UI线程上更新状态
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                Mqttisconneted = DeviceManager.IsDeviceConnected("device1") &&
                                 DeviceManager.IsDeviceConnected("device2");
            });
        }
    }
}